package 笔试.同行者实习;

public class 轮流打印数字 {
    public static final Object lock = new Object();
    public static int num = 0;
    public static volatile boolean flag = true;

    public static void main(String[] args) {
        TaskA taskA = new TaskA();
        Thread threadA = new Thread(taskA);
        threadA.start();
        TaskB taskB = new TaskB();
        Thread threadB = new Thread(taskB);
        threadB.start();
    }

    public static class TaskA implements Runnable {
        @Override
        public void run() {
            while (num < 200) {
                if (flag) {
                    synchronized (lock) {
                        System.out.println(num++);
                        flag = false;
                    }
                }
            }
        }
    }

    public static class TaskB implements Runnable {
        @Override
        public void run() {
            while (num < 200) {
                if (!flag) {
                    synchronized (lock) {
                        System.out.println("===> " + num++);
                        flag = true;
                    }
                }
            }
        }
    }

}
